package com.xbongbong.pro.statistics.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormRefEntity;
import com.xbongbong.paas.model.PaasFormRefModel;
import com.xbongbong.paas.pojo.dto.PaymentSheetExplainsSingleDTO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.statistic.constant.RelatedProductConstant;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.pojo.dto.ChartEditDTO;
import com.xbongbong.pro.statistic.pojo.dto.ReInitDataDTO;
import com.xbongbong.pro.statistic.pojo.vo.DataInitVO;
import com.xbongbong.pro.statistic.service.DataWarehouseService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: 汪腾伟
 * @date: Created in 2021/8/20 14:46
 * @description： BI关联产品需要用到的一些脚本
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX+"/bi/relatedProduct")
public class BIRelatedProductScriptController {

    private static final Logger LOG = LoggerFactory.getLogger(BIRelatedProductScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private PaasFormRefModel paasFormRefModel;
    @Resource
    private DataWarehouseService dataWarehouseService;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    private static final String FORM_ID_STR = "formId";

    private static final String ORIGINALATTR= "originalAttr";

    private static final String SAASATTR = "saasAttr";

    /**
     * 处理tb_bi_pro_warehouse中的at_json（仅限产品子表单）、formId_attr、以及table_serial
     *
                        产品合同存es     产品合同表单解释
             产品编号    text_24   			    text_1
             产品名称 	text_23					text_91
             单价		num_30					num_1
             折扣		num_24					num_4
             售价		num_6					num_6
             数量		num_32					num_3
             备注		text_22					text_3
             销售单位		text_8					text_8
             售价小计     num_5					num_5
     *
     * @param paymentSheetExplainsSingleDTO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/customerChartSubProductHandle", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String customerChartSubProductHandle(@RequestBody @Valid PaymentSheetExplainsSingleDTO paymentSheetExplainsSingleDTO) throws Exception {
        try {
            if (!proBaseConfig.getXbbCode().equals(paymentSheetExplainsSingleDTO.getXbbCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
            }
            LocaleContextHolder.setLocale(Locale.CHINA);
            LOG.info("-----------迁移tb_chart_custom中的产品子表单数据-----------");
            long timeStart = DateTimeUtil.getInt();
            Map<String, String> fieldCompareMap = getFieldCompareMap();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Integer start = 0;
            //每次查询300条
            Integer pageNum = 300;
            Long idGte = 0L;
            param.put("start", start);
            param.put("pageNum", pageNum);
            param.put("orderByStr", "id asc");
            param.put("del", 0);
            while (true) {
                param.put("idGte", idGte);
                LOG.warn("处理进度：已处理到 tb_chart_custom.id = " + idGte);
                List<ChartEntity> chartEntityList = chartCustomModel.findEntitys(param);
                if (CollectionsUtil.isEmpty(chartEntityList)) {
                    break;
                }
                idGte = chartEntityList.get(chartEntityList.size() - 1).getId();
                //主要是为了存合同表单id列表
                Set<Long> linkFormIdSet = new HashSet<>();
                for (ChartEntity chartEntity : chartEntityList) {
                    JSONArray slaveSources = chartEntity.getSlaveSources();
                    if (Objects.isNull(slaveSources) || slaveSources.size() == 0) {
                        continue;
                    }
                    Long linkFormId = null;
                    for (int i = 0; i < slaveSources.size(); i++) {
                        JSONObject slaveJson = slaveSources.getJSONObject(i);
                        Integer slaveBusinessType = slaveJson.getInteger(StringConstant.BUSINESS_TYPE);
                        if (Objects.equals(slaveBusinessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                            linkFormId = slaveJson.getLong(FORM_ID_STR);
                            linkFormIdSet.add(linkFormId);
                        }
                    }
                }
                //去tb_paas_form_ref中查询出跟这个主业务对应的产品子表单的list
                Map<Long, PaasFormRefEntity> paasFormRefEntityMap = new HashMap<>();
                if (CollectionsUtil.isNotEmpty(linkFormIdSet)) {
                    Map<String, Object> paasFormRefMap = new HashMap<>();
                    paasFormRefMap.put("del", BasicConstant.ZERO);
                    paasFormRefMap.put("mainFormIdS", linkFormIdSet);
                    List<PaasFormRefEntity> paasFormRefEntities = paasFormRefModel.findEntitys(paasFormRefMap);
                    paasFormRefEntityMap = paasFormRefEntities.stream().collect(Collectors.toMap(PaasFormRefEntity::getMainFormId, a->a,(k1,k2)->k1));
                }
                List<ChartEntity> shouldUpdateChartEntitys = new ArrayList<>();
                //需要删除的图表
                List<Long> shouldDeleteIds = new ArrayList<>();
                for (ChartEntity chartEntity : chartEntityList) {
                    JSONObject driverSources = chartEntity.getDriverSources();
                    JSONArray slaveSources = chartEntity.getSlaveSources();
                    if (Objects.isNull(slaveSources) || slaveSources.size() == 0) {
                        continue;
                    }
                    Long linkFormId = null;
                    Long formId = driverSources.getLongValue(FORM_ID_STR);
                    Integer businessType = driverSources.getInteger(StringConstant.BUSINESS_TYPE);
                    for (int i = 0; i < slaveSources.size(); i++) {
                        JSONObject slaveJson = slaveSources.getJSONObject(i);
                        Integer slaveBusinessType = slaveJson.getInteger(StringConstant.BUSINESS_TYPE);
                        if (Objects.equals(slaveBusinessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                            linkFormId = slaveJson.getLong(FORM_ID_STR);
                        }
                    }
                    //目前只处理主表是产品（合同）子表单的就行
                    if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_PRODUCT.getCode())) {
                        if (Objects.isNull(linkFormId)) {
                            shouldDeleteIds.add(chartEntity.getId());
                            continue;
                        }
                        LOG.info("chartEntityId======:{}, linkFormId=========:{}",chartEntity.getId(), linkFormId);
                        PaasFormRefEntity paasFormRefEntity = paasFormRefEntityMap.get(linkFormId);
                        if (Objects.isNull(paasFormRefEntity)) {
                            continue;
                        }
                        Long subProductFormId = paasFormRefEntity.getFormId();
                        driverSources.put(FORM_ID_STR, subProductFormId);
                        String linkAttr = driverSources.getString("linkAttr");
                        String linkAttrB = driverSources.getString("linkAttrB");
                        String linkAttrC = driverSources.getString("linkAttrC");
                        String linkAttrD = driverSources.getString("linkAttrD");
                        String linkAttrE = driverSources.getString("linkAttrE");
                        //根据之前ContractProductSubFormEnum这个枚举里面num_21是用来关联合同的attr,现在要改成我们新的规则
                        if (Objects.equals(linkAttr, "num_21")) {
                            driverSources.put("linkAttr", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                            driverSources.put("linkAttrCopy", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                        }
                        if (Objects.equals(linkAttrB, "num_21")) {
                            driverSources.put("linkAttrB", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                            driverSources.put("linkAttrBCopy", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                        }
                        if (Objects.equals(linkAttrC, "num_21")) {
                            driverSources.put("linkAttrC", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                            driverSources.put("linkAttrCCopy", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                        }
                        if (Objects.equals(linkAttrD, "num_21")) {
                            driverSources.put("linkAttrD", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                            driverSources.put("linkAttrDCopy", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                        }
                        if (Objects.equals(linkAttrE, "num_21")) {
                            driverSources.put("linkAttrE", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                            driverSources.put("linkAttrECopy", RelatedProductConstant.LINK_MAINBUSINESS_ATTR);
                        }
                        //处理display_attr字段
                        JSONArray displayAttrArray = chartEntity.getDisplayAttr();
                        if (Objects.nonNull(displayAttrArray) && displayAttrArray.size() >BasicConstant.ZERO) {
                            for (int i = 0; i < displayAttrArray.size(); i++) {
                                JSONObject displayAttrJson = displayAttrArray.getJSONObject(i);
                                Integer displayBusinessType = displayAttrJson.getInteger(StringConstant.BUSINESS_TYPE);
                                if (Objects.equals(displayBusinessType, XbbRefTypeEnum.CONTRACT_PRODUCT.getCode())) {
                                    displayAttrJson.put(FORM_ID_STR, paasFormRefEntity.getFormId());
                                    String originalAttr = displayAttrJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        //displayAttrJson.put(SAASATTR, fieldCompareMap.get(originalAttr));
                                        displayAttrJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = displayAttrJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理summary_attr
                        JSONArray summaryAttr = chartEntity.getSummaryAttr();
                        if (Objects.nonNull(summaryAttr) && summaryAttr.size() > 0) {
                            for (int p = 0; p < summaryAttr.size(); p++) {
                                JSONObject summaryJson = summaryAttr.getJSONObject(p);
                                Long summaryFormId = summaryJson.getLong(FORM_ID_STR);
                                if (Objects.equals(summaryFormId, formId)) {
                                    summaryJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = summaryJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        summaryJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = summaryJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理row_group_attr
                        JSONArray rowGroupAttr = chartEntity.getRowGroupAttr();
                        if (Objects.nonNull(rowGroupAttr) && rowGroupAttr.size() > 0) {
                            for (int m = 0; m < rowGroupAttr.size(); m++) {
                                JSONObject rowGroupJson = rowGroupAttr.getJSONObject(m);
                                Long rowGroupFormId = rowGroupJson.getLong(FORM_ID_STR);
                                if (Objects.equals(rowGroupFormId, formId)) {
                                    rowGroupJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = rowGroupJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        rowGroupJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                       //rowGroupJson.put(SAASATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = rowGroupJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理col_group_attr
                        JSONArray colGroupAttr = chartEntity.getColGroupAttr();
                        if (Objects.nonNull(colGroupAttr) && colGroupAttr.size() > 0) {
                            for (int k = 0; k < colGroupAttr.size(); k++) {
                                JSONObject colGroupAttrJson = colGroupAttr.getJSONObject(k);
                                Long colGroupFormId = colGroupAttrJson.getLong(FORM_ID_STR);
                                if (Objects.equals(colGroupFormId, formId)) {
                                    colGroupAttrJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = colGroupAttrJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        colGroupAttrJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                        //colGroupAttrJson.put(SAASATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = colGroupAttrJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理chart_classify
                        JSONArray chartClassify = chartEntity.getChartClassify();
                        if (Objects.nonNull(chartClassify) && chartClassify.size() > 0) {
                            for (int q = 0; q < chartClassify.size(); q++) {
                                JSONObject chartClaaifyJson = chartClassify.getJSONObject(q);
                                Long chartClassifyFormId = chartClaaifyJson.getLong(FORM_ID_STR);
                                if (Objects.equals(chartClassifyFormId, formId)) {
                                    chartClaaifyJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = chartClaaifyJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        chartClaaifyJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = chartClaaifyJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理chart_series
                        JSONArray chartSeries = chartEntity.getChartSeries();
                        if (Objects.nonNull(chartSeries) && chartSeries.size() > 0) {
                            for (int s = 0; s < chartSeries.size(); s++) {
                                JSONObject chartSerialJson = chartSeries.getJSONObject(s);
                                Long chartSerialFormId = chartSerialJson.getLong(FORM_ID_STR);
                                if (Objects.equals(chartSerialFormId, formId)) {
                                    chartSerialJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = chartSerialJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        chartSerialJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = chartSerialJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }

                        //处理chart_value
                        JSONArray chartValue = chartEntity.getChartValue();
                        if (Objects.nonNull(chartValue) && chartValue.size() > 0) {
                            for (int r = 0; r < chartValue.size(); r++) {
                                JSONObject chartJson = chartValue.getJSONObject(r);
                                Long chartFormId = chartJson.getLong(FORM_ID_STR);
                                if (Objects.equals(chartFormId, formId)) {
                                    chartJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = chartJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        chartJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = chartJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理penetrate_attr
                        JSONArray penetrateAttr = chartEntity.getPenetrateAttr();
                        if (Objects.nonNull(penetrateAttr) && penetrateAttr.size() > 0) {
                            for (int j = 0; j < penetrateAttr.size(); j++) {
                                JSONObject penetrateJson = penetrateAttr.getJSONObject(j);
                                Long penetrateFormId = penetrateJson.getLong(FORM_ID_STR);
                                if (Objects.equals(penetrateFormId, formId)) {
                                    penetrateJson.put(FORM_ID_STR, subProductFormId);
                                    String originalAttr = penetrateJson.getString(ORIGINALATTR);
                                    if (fieldCompareMap.containsKey(originalAttr)) {
                                        penetrateJson.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = penetrateJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        //处理formId_attr
                        JSONObject formIdAttrJson = chartEntity.getFormIdAttr();
                        JSONObject subProductFormInfoJson = formIdAttrJson.getJSONObject(String.valueOf(formId));
                        if (Objects.nonNull(subProductFormInfoJson)) {
                            JSONObject newSubProductFormInfoJson = new JSONObject();
                            Set<Map.Entry<String, Object>> entrySet = subProductFormInfoJson.entrySet();
                            for (Map.Entry<String, Object> entry : entrySet) {
                                if (fieldCompareMap.containsKey(entry.getKey())) {
                                    newSubProductFormInfoJson.put(fieldCompareMap.get(entry.getKey()), entry.getValue());
                                }else {
                                    newSubProductFormInfoJson.put(entry.getKey(), entry.getValue());
                                }
                            }
                            formIdAttrJson.remove(String.valueOf(formId));
                            formIdAttrJson.put(String.valueOf(subProductFormId), newSubProductFormInfoJson);
                        }
                        //处理selected_attr，这是一个复杂的过程
                        JSONObject selectedAttrJson = chartEntity.getSelectedAttr();
                        if (Objects.nonNull(selectedAttrJson) && selectedAttrJson.size() > 0) {
                            JSONObject newSelectedAttrJson = new JSONObject();
                            Set<Map.Entry<String, Object>> selectedAttrEntrySet = selectedAttrJson.entrySet();
                            for (Map.Entry<String, Object> entry : selectedAttrEntrySet) {
                                String oldShouldHandleKey = entry.getKey();
                                JSONObject oldShouldJson = (JSONObject) entry.getValue();
                                String[] splitKeyS = oldShouldHandleKey.split("-");
                                String prefixKey = splitKeyS[BasicConstant.ZERO];
                                Long oldValueSubProductFormId = Long.valueOf(splitKeyS[BasicConstant.ONE]);
                                String newShouldHandleKey = oldShouldHandleKey;
                                if (Objects.equals(formId, oldValueSubProductFormId)) {
                                    if (fieldCompareMap.containsKey(prefixKey)) {
                                        prefixKey = fieldCompareMap.get(prefixKey);
                                    }
                                }
                                if (Objects.equals(formId, oldValueSubProductFormId)) {
                                    newShouldHandleKey = prefixKey + "-" + subProductFormId;
                                    //这边需要处理一下每一个key对应的json
                                    Set<Map.Entry<String, Object>> oldValueEntry = oldShouldJson.entrySet();
                                    for (Map.Entry<String, Object> oldValue : oldValueEntry) {
                                        if (Objects.equals(oldValue.getKey(), FORM_ID_STR) && Objects.equals(Long.valueOf(String.valueOf(oldValue.getValue())), formId)) {
                                            oldValue.setValue(subProductFormId);
                                        } else if (Objects.equals(oldValue.getKey(), ORIGINALATTR) && fieldCompareMap.containsKey(oldValue.getValue())) {
                                            oldValue.setValue(fieldCompareMap.get(oldValue.getValue()));
                                        }
                                    }
                                }
                                //重新赋值一下
                                newSelectedAttrJson.put(newShouldHandleKey, oldShouldJson);
                            }
                            chartEntity.setSelectedAttr(newSelectedAttrJson);
                        }
                        //处理computed_attr
                        JSONArray computedAttr = chartEntity.getComputedAttr();
                        if (Objects.nonNull(computedAttr) && computedAttr.size() > 0) {
                            for (int t = 0; t < computedAttr.size(); t++) {
                                JSONObject computedAttrJson = computedAttr.getJSONObject(t);
                                Long computedFormId = computedAttrJson.getLong(FORM_ID_STR);
                                if (Objects.equals(computedFormId, formId)) {
                                    computedAttrJson.put(FORM_ID_STR, subProductFormId);
                                    JSONObject formularInfoJson = computedAttrJson.getJSONObject("formulaInfo");
                                    handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                }
                                //处理公式computednum_attr
                                JSONArray computedNumAttr = chartEntity.getComputedNumAttr();
                                if (Objects.nonNull(computedNumAttr) && computedNumAttr.size() > 0) {
                                    for (int v = 0; v < computedNumAttr.size(); v++) {
                                        JSONObject computedNumAttrJSONObject = computedNumAttr.getJSONObject(v);
                                        Long computedNumFormId = computedNumAttrJSONObject.getLong(FORM_ID_STR);
                                        if (Objects.equals(computedNumFormId, formId)) {
                                            computedNumAttrJSONObject.put(FORM_ID_STR, subProductFormId);
                                            String originalAttr = computedNumAttrJSONObject.getString(ORIGINALATTR);
                                            if (fieldCompareMap.containsKey(originalAttr)) {
                                                computedNumAttrJSONObject.put(ORIGINALATTR, fieldCompareMap.get(originalAttr));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //处理chart_value_second
                        JSONArray chartValueSecond = chartEntity.getChartValueSecond();
                        if (Objects.nonNull(chartValueSecond) && chartValueSecond.size() > 0) {
                            for (int w = 0; w < chartValueSecond.size(); w++) {
                                JSONObject chartValueJson = chartValueSecond.getJSONObject(w);
                                Long chartValueFormId = chartValueJson.getLong(FORM_ID_STR);
                                if (Objects.equals(chartValueFormId, formId)) {
                                    chartValueJson.put(FORM_ID_STR, subProductFormId);
                                    String attr = chartValueJson.getString("attr");
                                    if (fieldCompareMap.containsKey(attr)) {
                                        chartValueJson.put("attr", fieldCompareMap.get(attr));
                                    }
                                    //处理计算公式字段
                                    JSONObject formularInfoJson = chartValueJson.getJSONObject("formulaInfo");
                                    if (Objects.nonNull(formularInfoJson)) {
                                        handleComputerField(formularInfoJson, formId, subProductFormId, fieldCompareMap);
                                    }
                                }
                            }
                        }
                        shouldUpdateChartEntitys.add(chartEntity);
                    }
                }
                //批量更新操作
                if (CollectionsUtil.isNotEmpty(shouldUpdateChartEntitys)) {
                    chartCustomModel.updateBatchNoCorpId(shouldUpdateChartEntitys);
                }
                //批量删除操作，这边设置为del特殊标识为2
                if (CollectionsUtil.isNotEmpty(shouldDeleteIds)) {
                    chartCustomModel.updateBatchDeleteTag(shouldDeleteIds, 2);
                }
            }
            LOG.warn("-----------time consume warehouseSubProductHandle:" + (DateTimeUtil.getInt() - timeStart));
            LOG.warn("-----------/script/bi/relatedProduct/warehouseSubProductHandle over");
        } catch (Exception e) {
            LOG.error("/script/bi/relatedProduct/warehouseSubProductHandle error", e);
        }
        return JSON.toJSONString("{\"msg\":\"success\"}");
    }


    /**
     * 获取字段对比的map
     * 产品编号、 产品名称、单价、折扣、售价、数量、备注、销售单位、售价小计
     *
     * @return
     */
    private Map<String, String> getFieldCompareMap() {
        Map<String, String> fieldCompareMap = new HashMap<>();
        fieldCompareMap.put("text_24", "text_1");
        fieldCompareMap.put("text_23", "text_91");
        fieldCompareMap.put("num_30",  "num_1");
        fieldCompareMap.put("num_24", "num_4");
        fieldCompareMap.put("num_6", "num_6");
        fieldCompareMap.put("num_32", "num_3");
        fieldCompareMap.put("text_22", "text_3");
        fieldCompareMap.put("text_8", "text_8");
        fieldCompareMap.put("num_5", "num_5");
        return fieldCompareMap;
    }


    /**
     * 处理计算公式字段
     *
     * @param formularInfoJson 计算公式字段
     * @param formId 表单id
     * @param subProductFormId 产品子表单id
     * @param fieldCompareMap 字段对比map
     * @return
     */
    private void handleComputerField(JSONObject formularInfoJson, Long formId, Long subProductFormId, Map<String,String> fieldCompareMap) {
        JSONObject fieldJson = formularInfoJson.getJSONObject("fields");
        JSONArray fieldJsonArray = fieldJson.getJSONArray(String.valueOf(formId));
        JSONArray newFieldJsonArray = new JSONArray();
        if (Objects.nonNull(fieldJsonArray) && fieldJsonArray.size() > 0) {
            for (int u = 0; u < fieldJsonArray.size(); u++) {
                String keyValue = fieldJsonArray.getString(u);
                if (fieldCompareMap.containsKey(keyValue)) {
                    newFieldJsonArray.add(fieldCompareMap.get(keyValue));
                }else {
                    newFieldJsonArray.add(keyValue);
                }
            }
        }
        fieldJson.remove(String.valueOf(formId));
        fieldJson.put(String.valueOf(subProductFormId), newFieldJsonArray);
        //处理公式formula
        String formula = formularInfoJson.getString("formula");
        Map<String, String> shouldFilterMap = new HashMap<>();
        if (StringUtil.isNotEmpty(formula)) {
            String[] formulaArray = RegexUtil.getFormulaAttr(formula);
            for (String formulStr : formulaArray) {
                String[] secondFormulArray = formulStr.split("[{,.,}]");
                String secondeFormulFormId = secondFormulArray[1];
                String secondeFormnulAttr = secondFormulArray[2];
                if (Objects.equals(secondeFormulFormId, String.valueOf(formId))) {
                    String shouldReplaceValue = secondeFormulFormId + "." + secondeFormnulAttr;
                    String newValue = subProductFormId + "." + fieldCompareMap.get(secondeFormnulAttr);
                    shouldFilterMap.put(shouldReplaceValue, newValue);
                }
            }
            for (Map.Entry<String, String> entry: shouldFilterMap.entrySet()) {
                formula = formula.replace(entry.getKey(), entry.getValue());
            }
        }
        formularInfoJson.put("formula", formula);
        JSONObject labelMapJson = formularInfoJson.getJSONObject("labelMap");
        JSONObject newLabelMapJson = new JSONObject();
        if (Objects.nonNull(labelMapJson) && labelMapJson.size() > 0) {
            for (Map.Entry<String, Object> mapEntry : labelMapJson.entrySet()) {
                String[] keyArray = mapEntry.getKey().split("\\.");
                String value = (String)mapEntry.getValue();
                String keyOne = keyArray[0];
                String keyTwo = keyArray[1];
                if (Objects.equals(keyOne, String.valueOf(formId))) {
                    keyOne = String.valueOf(subProductFormId);
                }
                if (Objects.equals(keyArray[0], String.valueOf(formId)) && fieldCompareMap.containsKey(keyTwo)) {
                    keyTwo = fieldCompareMap.get(keyTwo);
                }
                String newKey = keyOne + "." + keyTwo;
                newLabelMapJson.put(newKey, value);
            }
        }
        formularInfoJson.put("labelMap", newLabelMapJson);
    }


    @RequestMapping(value = "/reInitContractProductBIData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String reInitContractProductBIData(@RequestBody @Valid ReInitDataDTO reInitDataDTO, BindingResult br) {
        XbbResponse<DataInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(reInitDataDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(reInitDataDTO)) {
                    response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                    return JSON.toJSONString(response);
                }
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                if(!proBaseConfig.getXbbCode().equals(reInitDataDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                //SELECT * from tb_chart_custom WHERE JSON_EXTRACT(driver_sources,'$.businessType')=204 AND muti=0 AND del=0
                //线上也就800多
                Map param = new HashMap(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("muti",0);
                param.put("del",0);
                param.put("diySql","JSON_EXTRACT(driver_sources,'$.businessType')=204");
                List<ChartEntity> chartEntityList = chartCustomModel.findDiyEntitys(param);
                LOG.info("=====size==========="+chartEntityList.size());
                int i = 0;
                for (ChartEntity chartEntity : chartEntityList) {
                    try {
                        ChartEditDTO chartEditDTO = new ChartEditDTO();
                        chartEditDTO.setCorpid(chartEntity.getCorpid());
                        chartEditDTO.setChartId(chartEntity.getId());
                        chartEditDTO.setStartRun(true);
                        dataWarehouseService.initData(chartEditDTO);
                        i++;
                        LOG.info("=====i==========="+i);
                    } catch (Exception e) {
                        LOG.error("errorId==="+chartEntity.getId(),e);
                    }
                }
                DataInitVO dataInitVO = new DataInitVO();
                response = new XbbResponse<>(dataInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


}
